<?php
/**
 * Description: 获取用户已购课程及课堂信息（缓存列表）
 * User: devforma
 * Date: 15/10/12
 * Time: 21:03
 */

class GetPurchasedCourses implements iController {

    private $now;

    const CLASS_STATUS_NOTEND = 0;
    const CLASS_STATUS_TRANSFROMING = 1;
    const CLASS_STATUS_CANDOWNLOAD = 2;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (validateUser($queryArgs) !== 1)
            return genOutput(1000);

        $purchased = $cmsdb->getCol('SELECT `product_id` FROM `relation_user_product` WHERE `user_id`=:uid AND `product_type`="zhiboke"',
            array(':uid' => $queryArgs['user_id']));

        if (empty($purchased))
            return genOutput(1, array('list' => array()));

        $this->now = time();

        $purchasedStr = implode(',', $purchased);

        $purchasedCourses = $cmsdb->getResults("SELECT `id`, `course_name` FROM `data_live_course`
        WHERE `id` IN ({$purchasedStr}) ORDER BY `is_sticked` DESC, `last_modified` DESC, `id` DESC");

        $list = array();
        foreach ($purchasedCourses as $course) {
            $data = array(
                'id' => intval($course->id),
                'name' => $course->course_name,
                'classes' => array(),
                'lector' => ''
            );

            $classes = getCourseClassIds($course->id);
            $lectors = array();

            foreach ($classes as $class) {
                $classInfo = getLiveClassInfo($class);

                $data['classes'][] = array(
                    'id' => intval($class),
                    'name' => $classInfo->class_name,
                    'room_id' => $classInfo->room_id,
                    'start_time' => $classInfo->start_time,
                    'end_time' => $classInfo->end_time,
                    'lector' => $classInfo->lector_name,
                    'status' => $this->checkStatus(strtotime($classInfo->end_time))
                );

                if (!in_array($classInfo->lector_name, $lectors, true)) {
                    $lectors[] = $classInfo->lector_name;
                }
            }

            $data['lector'] = implode(' ', $lectors);
            $list[] = $data;
        }

        return genOutput(1, array('list' => $list));
    }

    /**
     * 检查课堂状态
     *
     * @param $endTime
     * @return int
     */
    private function checkStatus($endTime) {
        if ($this->now <= $endTime) {
            return GetPurchasedCourses::CLASS_STATUS_NOTEND;
        } elseif ($endTime < $this->now && $this->now <= $endTime + 8*60*60) {
            return GetPurchasedCourses::CLASS_STATUS_TRANSFROMING;
        } else {
            return GetPurchasedCourses::CLASS_STATUS_CANDOWNLOAD;
        }
    }
}